'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

var app = angular.module("myApp", ['ui.bootstrap', 'ui.bootstrap.treeview2']);

var treeViewTemplate = '\n<tree-view ng-if="graphTree != null && graphTree.g != null" tree-service="graphTree" node-label="text"></tree-view>\n';

app.controller("reportController", ['$scope', '$compile', '$sce', function ($scope, $compile, $sce) {
    $scope.toJSON = function (val) {
        return toJSON(val);
    };
    var request = getRequest();
    $scope.faultId = request["faultId"];
    // $scope.featureIds = JSON.parse(request["featureIds"]);
    console.info(request["matchedNodes"]);
    $scope.matchedNodes = JSON.parse(request["matchedNodes"]);
    $scope.unknownNodes = JSON.parse(request["unknownNodes"]);
    $scope.channels = JSON.parse(request["channels"]);
    $scope.timestamp = parseInt(request["timestamp"]);
    $scope.last_timestamp = parseInt(request["last_timestamp"]);

    $scope.sequence = request["reportId"];
    $scope.reasons = [];

    var queryUrl = 'start n=node(' + $scope.faultId + ') match (n)-[*]->(p) return n,p';
    $scope.faultUrl = $sce.trustAsResourceUrl('../browser/NeoEmbed.html?query=' + encodeURIComponent(queryUrl).replace(/=/g, '%3d'));

    $scope.graphTree = new NodeTreeView();
    Graph.loadGraph($scope.faultId, function (g) {
        $scope.graph = g;
        var nodesList = [].concat(_toConsumableArray(g.nodes.values()));

        var _loop = function _loop(nd) {
            if ($scope.matchedNodes.some(function (nid) {
                return nid == nd.id;
            })) {
                nd.isMatched = true;
            }
            if ($scope.unknownNodes.some(function (nid) {
                return nid == nd.id;
            })) {
                nd.unknown = true;
            }
        };

        var _iteratorNormalCompletion = true;
        var _didIteratorError = false;
        var _iteratorError = undefined;

        try {
            for (var _iterator = nodesList[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                var nd = _step.value;

                _loop(nd);
            }
        } catch (err) {
            _didIteratorError = true;
            _iteratorError = err;
        } finally {
            try {
                if (!_iteratorNormalCompletion && _iterator.return) {
                    _iterator.return();
                }
            } finally {
                if (_didIteratorError) {
                    throw _iteratorError;
                }
            }
        }

        $scope.fault = nodesList.filter(function (node) {
            return node.$type == "Fault";
        })[0];
        $scope.features = nodesList.filter(function (node) {
            return node.$type == 'Feature' && node.isMatched;
        });

        $scope.relatedComponents = [];

        $scope.features.forEach(function (f, index) {
            ComponentNode.loadComponentsFrom(f.id, function (components) {
                var rset = new Set($scope.relatedComponents);
                components.forEach(function (c) {
                    return rset.add(c.name);
                });
                $scope.relatedComponents = [].concat(_toConsumableArray(rset));
                $scope.$apply();
            });
        });
        var matchedOutIds = $scope.features.filter(function (f) {
            return f.isMatched;
        }).map(function (f) {
            return f.outId;
        }).filter(function (id) {
            return id != 0;
        });
        console.info(matchedOutIds);
        $scope.reasons = nodesList.filter(function (node) {
            return node.$type == 'Reason';
        }).sort(function (a, b) {
            return a > b;
        });
        $scope.reasons.filter(function (r) {
            return matchedOutIds.some(function (id) {
                return id == r.outId;
            });
        }).forEach(function (r) {
            return r.isMatched = true;
        });

        $scope.gridShowReasons = $scope.reasons.filter(function (node) {
            return node.outId && node.outId != 0;
        });

        // $scope.graphTree.nodes = [$scope.graph.toJsonTree()];
        $scope.graphTree.g = g;
        console.info($scope.graphTree);
        $scope.graphTree.collapseAll();

        var tp = $compile(treeViewTemplate)($scope);
        angular.element("#treeDiv").html("").append(tp);

        $scope.$apply();
    });

    $scope.getNow = function () {
        return new Date($scope.timestamp);
    };
    //        FaultNode.loadFaults.callbacks.push(()=>$scope.faults=FaultNode.faults);
}]);

app.filter("toTimeSpan", [function () {
    return function (intVal) {
        var ms = intVal % 1000;
        intVal -= ms;
        intVal /= 1000;
        var s = intVal % 60;
        intVal -= s;
        intVal /= 60;
        var min = intVal % 60;
        intVal -= min;
        intVal /= 60;
        var hour = intVal % 24;
        intVal -= hour;
        var day = intVal / 24;
        var f = function f(x, label) {
            return x > 0 ? "" + x + label : "";
        };
        return f(day, "d") + f(hour, "h") + f(min, "min") + f(s, "s") + f(ms, "ms");
    };
}]);

app.filter('startX', [function () {
    return function (array, size) {
        if (array.length <= size) return array.map(function (x) {
            return x.toFixed(2);
        }).join(",");
        return array.slice(0, 2).map(function (x) {
            return x.toFixed(2);
        }).join(",") + "等" + array.length + "项";
    };
}]);

function getRequest() {
    var url = location.search; //获取url中"?"符后的字串
    var theRequest = {};
    if (url.indexOf("?") !== -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
            theRequest[strs[i].split("=")[0]] = decodeURI(strs[i].split("=")[1]);
        }
    }
    return theRequest;
}
